package com.lc.railway.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hjq.bar.TitleBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.railway.R;
import com.lc.railway.http.request.ApiCommunicationApi;
import com.lc.railway.http.request.ApiNewsShowApi;
import com.lc.railway.http.request.CollectAddApi;
import com.lc.railway.http.request.CollectDelApi;
import com.lc.railway.http.response.ApiNewsShowBean;
import com.lc.railway.other.IntentKey;
import com.lc.railway.sqlite.BrowseDao;
import com.lc.railway.ui.dialog.UpdateNewsDialog;
import com.lc.railway.util.CourseUtils;
import com.lc.railway.util.HtmlUtils;
import com.lc.railway.util.SPUtil;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewsDeatailsActivity extends WaterActivity {
    @BindView(R.id.title_bar_top)
    TitleBar titleBarTop;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_clone)
    TextView tvClone;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.tv_hits)
    TextView tvHits;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    private String appendix;
    private BrowseDao browseDao;
    private String date;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_newsdeatails;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        titleBarTop.setTitle(getIntent().getStringExtra("title"));

        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);//设置webview推荐使用的窗口
        webSettings.setLoadWithOverviewMode(true);//设置webview加载的页面的模式
        webSettings.setDisplayZoomControls(false);//隐藏webview缩放按钮
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {

                LogUtil.i("webview加载结束");
            }
        });
        if (CourseUtils.isNullOrEmpty(getIntent().getStringExtra("type"))) {
            api_news_lists();
            date = getDate(Calendar.getInstance().getTimeInMillis() / 1000);
            browseDao = new BrowseDao(this);
            if (!browseDao.isHasRecord(getIntent().getStringExtra("id"))) {
                browseDao.add(getIntent().getStringExtra("title"), getIntent().getStringExtra("content"), getIntent().getStringExtra("picurl"), date, getIntent().getStringExtra("time"), getIntent().getStringExtra("id"));
            }
        } else {
            llTop.setVisibility(View.GONE);
            rlBottom.setVisibility(View.GONE);
            api_news();
        }
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    collect_add();
                } else {
                    collect_del();
                }
            }
        });

    }

    private void collect_del() {
        EasyHttp.post(this)
                .api(new CollectDelApi().setMember_id(SPUtil.get(this, IntentKey.ID, "")).setNid(getIntent().getStringExtra("id")))
                .request(new HttpCallback<ApiNewsShowBean>(this) {
                    @Override
                    public void onSucceed(ApiNewsShowBean data) {

                        if (data.getError_code() == 200) {
//                            toast("取消收藏");

                        }
                    }
                });
    }

    private void collect_add() {
        EasyHttp.post(this)
                .api(new CollectAddApi().setMember_id(SPUtil.get(this, IntentKey.ID, "")).setNid(getIntent().getStringExtra("id")))
                .request(new HttpCallback<ApiNewsShowBean>(this) {
                    @Override
                    public void onSucceed(ApiNewsShowBean data) {

                        if (data.getError_code() == 200) {
//                           toast("收藏成功");

                        }
                    }
                });

    }

    private void api_news_lists() {
        EasyHttp.post(this)
                .api(new ApiNewsShowApi().setId(getIntent().getStringExtra("id")).setMember_id(SPUtil.get(this, IntentKey.ID, "")))
                .request(new HttpCallback<ApiNewsShowBean>(this) {
                    @Override
                    public void onSucceed(ApiNewsShowBean data) {

                        if (data.getError_code() == 200) {
                            if (data.getData().getShow().getIs_collect() == 0) {
                                checkbox.setChecked(false);
                            } else {
                                checkbox.setChecked(true);
                            }
                            title.setText(data.getData().getShow().getTitle());
                            tvDate.setText("时间：" + data.getData().getShow().getCreate_time());
                            appendix = data.getData().getShow().getAppendix();
                            tvHits.setText("浏览量" + data.getData().getShow().getHits());
                            String html = HtmlUtils.setHtml(data.getData().getShow().getContent());
                            webview.loadDataWithBaseURL(null, html
                                    , "text/html", "UTF-8", null);
//                            mBinding.webview.loadData(html, "text/html; charset=UTF-8", null);

                        }
                    }
                });


    }

    private void api_news() {
        EasyHttp.post(this)
                .api(new ApiCommunicationApi().setId(getIntent().getStringExtra("id")).setType(getIntent().getStringExtra("type")))
                .request(new HttpCallback<String>(this) {
                    @Override
                    public void onSucceed(String data) {


                        webview.loadDataWithBaseURL(null, data
                                , "text/html", "UTF-8", null);
//                            mBinding.webview.loadData(html, "text/html; charset=UTF-8", null);


                    }
                });


    }

    private String getDate(long milliSeconds) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        // Create a calendar object that will convert the date and time value in
        // milliseconds to date.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds * 1000L);
        return formatter.format(calendar.getTime());
    }

    @OnClick(R.id.tv_clone)
    public void onClick() {
        if (CourseUtils.isNotNullOrEmpty(appendix)) {
            // 下载原文对话框
            new UpdateNewsDialog.Builder(this)
                    // 下载 URL
                    .setDownloadUrl(appendix)
                    .show();
        }

    }
}
